﻿using System;
using System.Threading;

namespace KingRoad.EPM.Web.Areas.CompletionMaterials.CompletionMaterialsFramework.Common
{
    /// <summary>
    /// 代码Try-Catch统一模块
    /// </summary>
    public class TryCatchCommand
    {
        /// <summary>
        /// 普通的Try-Catch
        /// </summary>
        /// <param name="action"></param>
        /// <returns></returns>
        public static bool TryExec(Action action)
        {
            try
            {
                action();
                return true;
            }
            catch (Exception ex)
            {
                if (!(ex is ThreadAbortException))

                    // 保存日志
                    PersonnelLog.PersonnelLogFramework.Common.TraceException.TraceMsgLog(ex);
            }
            return false;
        }
        /// <summary>
        ///  带返异常信息的Try-Catch
        /// </summary>
        /// <param name="action">要执行的方法</param>
        /// <param name="actionFailed">异常信息</param>
        /// <returns></returns>
        public static bool TryExec(Action action, Action<Exception> actionFailed)
        {
            try
            {
                action();
                return true;
            }
            catch (Exception ex)
            {
                // 保存日志
                PersonnelLog.PersonnelLogFramework.Common.TraceException.TraceMsgLog(ex);
                actionFailed(ex);
            }
            return false;
        }
        /// <summary>
        /// 带返回值的Try-Catch
        /// </summary>
        /// <typeparam name="T">返回值类型</typeparam>
        /// <param name="func">具体执行方法</param>
        /// <returns></returns>
        public static T TryExec<T>(Func<T> func)
        {
            T t = default(T);
            try
            {
                t = func();
            }
            catch (Exception ex)
            {
                PersonnelLog.PersonnelLogFramework.Common.TraceException.TraceMsgLog(ex);
            }
            return t;
        }
    }
}
